package com.yx.service.impl;

import com.alibaba.fastjson.JSON;
import com.yx.service.ISearchGoodsService;
import com.yx.vo.Goods;
import com.yx.vo.SearchGoodsParam;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Classname SearchGoodsServiceImpl
 * @Date 2021/07/12 19:08
 * @Author by yx
 * @Description TODO:
 */
@Service
public class SearchGoodsServiceImpl implements ISearchGoodsService {

    @Value("${es.index}")
    private String index;
    @Value("${es.type}")
    private String type;
    @Autowired
    private RestHighLevelClient client;

    @Override
    public void addGoods(Goods goods) throws IOException {
        //1.创建新增请求;以商品的id作为es里面的id
        IndexRequest request = new IndexRequest(index, type, goods.getId()+"");
        //2.添加数据
        request.source(JSON.toJSONString(goods), XContentType.JSON);
        //3.操作es
        IndexResponse index = client.index(request, RequestOptions.DEFAULT);
        //4.获取返回结果
        System.out.println(index.getResult());

    }

    @Override
    public List<Goods> search(SearchGoodsParam param) throws IOException {
        // 创建一个list集合用于存放封装好的数据
        List<Goods> list = new ArrayList<>();

        //1.创建请求
        SearchRequest request = new SearchRequest();
        //2.设置索引和类型
        request.indices(index);
        request.types(type);
        //3.设置查询条件:高亮排序
        SearchSourceBuilder builder = SearchSourceBuilder.searchSource();
        //设置高亮显示
        HighlightBuilder highlight = new HighlightBuilder();
        //设置高亮的属性
        highlight.field("gname");
        //设置前后缀
        highlight.preTags("<font color='red'>");
        highlight.postTags("</font>");
        //设置字体大小
        highlight.fragmentSize(50);
        builder.highlighter(highlight);
        //添加排序规则
        if (param.getOrderFiled()!=null) {
            switch (param.getOrderFiled()){
                case 1:
                    builder.sort("id", SortOrder.DESC);
                    break;
                case 2:
                    builder.sort("gprice", SortOrder.DESC);
                    break;
                case 3:
                    builder.sort("gtypePid", SortOrder.DESC);
                    break;
                default:
                    break;
            }
        }
        // 把排序规则设置给rquest对象
        request.source(builder);

        if (!StringUtils.isEmpty(param.getKeyword())) {
            //关键字不为空时,按照关键字查询
//            request.source(builder.query(QueryBuilders.multiMatchQuery(param.getKeyword(), "gname","gdesc")));
            request.source().query(QueryBuilders.multiMatchQuery(param.getKeyword(), "gname","gdesc"));
        }
        if (param.getType()!=null) {
            // 类型不为空,按照类型查询
//            request.source(builder.query(QueryBuilders.termQuery("gtypeCid", param.getType())));
            request.source().query(QueryBuilders.termQuery("gtypeCid", param.getType()));
        }

        //4.查询es
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        //5.json解析,封装
        //获取查询的数据
        SearchHit[] hits = search.getHits().getHits();
        Goods goods = null;
        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            goods = new Goods();
            try {
                //赋值(通过属性映射完成赋值)
                BeanUtils.populate(goods, sourceAsMap);

                //判断是否有高亮,有则替换
                HighlightField gname = hit.getHighlightFields().get("gname");
                if (gname!=null){
                    // 高亮部分数据格式: [gname], fragments[[<font color='red'>海飞丝</font>洗发水]]
                    String string = gname.getFragments()[0].toString();
                    goods.setGname(string);
                }

                list.add(goods);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        /*// 测试高亮为什么没有效果:获取高亮数据，输出
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println("高亮: "+hit.getHighlightFields().get("gname"));
        }
        // 获取最终显示结果
        for (Goods goods1 : list) {
            System.out.println(goods.getGname());
        }*/
        return list;
    }
}
